// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using InterpriseSuiteEcommerceCommon;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace InterpriseSuiteEcommerceControls.Validators
{
    public class RequiredInputValidator : InputValidator
    {
        private Control _controlToValidate;

        public RequiredInputValidator(Control controlToValidate, string errorMessage) : this(controlToValidate, errorMessage, null) { }

        public RequiredInputValidator(Control controlToValidate, string errorMessage, InputValidator next)
            : base(errorMessage, next)
        {
            _controlToValidate = controlToValidate;
        }

        public override bool SupportsClientSideValidation
        {
            get { return true; }
        }

        protected override bool EvaluateIsValid()
        {
            ITextControl controlAsTextBox = _controlToValidate as ITextControl;
            if (null != controlAsTextBox)
            {
                var txt = controlAsTextBox as TextBox;
                if (txt != null && txt.ReadOnly) { return true; }

                return !CommonLogic.IsStringNullOrEmpty(controlAsTextBox.Text);
            }

            HtmlInputControl controlAsInputControl = _controlToValidate as HtmlInputControl;
            if(null != _controlToValidate)
            {
                return !CommonLogic.IsStringNullOrEmpty(controlAsInputControl.Value);
            }

            return false;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        }

        public override string RenderInitialization()
        {
            return
                string.Format(
                    "new ise.Validators.RequiredFieldValidator('{0}', '{1}', {2})",
                    _controlToValidate.ClientID,
                    this.ErrorMessage,
                    RenderChainedValidatorInitialization()
                );
        }
    }
}
